const express = require("express")
const path = require("path")
const { check, validationResult } = require('express-validator')


const { db, genid } = require("../db/DbUtils.js")
const { EPSTATE } = require("../config/state.json")
const { jwts } = require("../utils/JsonWebtoken.js")
const { checks } = require("../utils/Validator.js")

const router = express.Router()


// 验证token接口
router.post("/token", async (req, res, next) => {
    // token验证
    let token = req.headers.authorization
    token = token.substring(0, token.indexOf(","))
    let user_id = jwts.verifyToken(token)
    if (user_id === null || user_id === undefined) {
        res.send({
            code: 10011
        })
        return
    }
})


// 登录
router.post("/", async (req, res, next) => {

    //! 缺少验证！

    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }
    // checks.judge(req, res)

    let { user_account, user_password } = req.body

    const sql_login = "select * from `login` where `user_account` = ? and `user_password` = ?"
    let { err, rows } = await db.async.query(sql_login, [user_account, user_password])

    // console.log("rows[0].user_id", rows[0].user_id);

    if (err === null && rows.length > 0) {
        let user_token = jwts.generateToken(rows[0].user_id)
        res.header("Authorization", user_token)
        res.send(EPSTATE.EP200)
    } else {
        res.send(EPSTATE.EP401)
    }

})


// 创建账号
router.post("/register", async (req, res, next) => {

    let { user_account, user_password, user_email } = req.body
    let user_id = genid.NextId()

    // 将新创建的账号放入审查表以待核查
    const sql_login = "INSERT INTO `examine`(`user_id`, `user_account`, `user_password`, `user_email`) VALUES (?, ?, ?, ?)"
    let params = [user_id, user_account, user_password, user_email]

    let { err, rows } = await db.async.query(sql_login, params)

    if (!err) {
        res.send(EPSTATE.EP200)
    } else {
        res.send({
            code: 500,
            msg: "bad"
        })
    }
})

module.exports = router;
